package cn.edu.hstc.wm.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.sina.weibo.sdk.openapi.CommentsAPI;

import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.bean.Comment;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.service.CommentService;
import cn.edu.hstc.wm.widget.CustomToast;
import android.annotation.SuppressLint;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

/**
 * 用户评论店铺的对话框
 */
public class GoCommentDialog extends DialogFragment implements OnClickListener {

	public static final String TAG = "GoCommentDialog";
	private static GoCommentDialog sDialog = null;
	private static Bundle sBundle = null;
	Store mStore;

	View rootView;

	/**
	 * 返回,提交
	 */
	ImageView backView, commitView;

	/**
	 * 评论内容
	 */
	EditText commentText;

	/**
	 * 评分等级
	 */
	RatingBar commentGrade;

	/**
	 * 获取该对话框实例的方法 ;点击点击同一个对象不会创建新的，加强利用
	 * 
	 * @param bundle
	 * @return
	 */
	public static GoCommentDialog newInstance(Bundle bundle) {
		if (sDialog == null || sBundle != bundle) {
			sDialog = new GoCommentDialog();
			sBundle = bundle;
		}

		sDialog.setArguments(bundle);
		return sDialog;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView");
		if (getDialog() != null) {
			getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); // 设置对话框无标题
			getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置背景透明
		}

		rootView = inflater.inflate(R.layout.go_comment_dialog_layout, container, false);
		getData();
		initView();
		return rootView;
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	public void onStart() {
		Log.d(TAG, "onStart");
		super.onStart();
		if (getDialog() != null) {

			// 获取宽度
			int fullWidth = getDialog().getWindow().getAttributes().width;

			// 不同版本api的方法
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
				Display display = getActivity().getWindowManager().getDefaultDisplay();
				Point size = new Point();
				display.getSize(size);
				fullWidth = size.x;
			} else {
				Display display = getActivity().getWindowManager().getDefaultDisplay();
				fullWidth = display.getWidth();
			}

			final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());

			// 有效显示区域
			int w = fullWidth - padding;
			int h = getDialog().getWindow().getAttributes().height;

			getDialog().getWindow().setLayout(w, h); // 设置位置
		}
	}

	private void initView() {

		backView = (ImageView) rootView.findViewById(R.id.iv_go_comment_dialog_back);
		commitView = (ImageView) rootView.findViewById(R.id.iv_go_comment_dialog_commit);

		commentText = (EditText) rootView.findViewById(R.id.et_go_comment_dialog_comment);
		commentGrade = (RatingBar) rootView.findViewById(R.id.ratingbar_go_comment_dialog_grade);

		backView.setOnClickListener(this);
		commitView.setOnClickListener(this);
	}

	private void getData() {
		mStore = (Store) getArguments().getSerializable(StoreItemInfo.INTENT_URL);
		Log.d(TAG, mStore.toString());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 返回了
		case R.id.iv_go_comment_dialog_back:
			dismiss();
			break;
		// 提交评论
		case R.id.iv_go_comment_dialog_commit:

			String content = commentText.getText().toString().trim();
			float score = commentGrade.getRating();

			if (content.length() == 0) { // comment.isEmpty() //api 9
				CustomToast.make(getActivity()).setText("评论内容不能为空!").show();
				break;
			}
			// 可以做一下输入内容的判断是否合法之类的

			// TODO 根据用户和store参数提交评论
			// User && Store --> Comment

			Comment comment = new Comment();
			comment.setStoreId(mStore.getId());
			comment.setComment(content);
			comment.setScore(score);
			comment.setUserName(((AppApplication) getActivity().getApplicationContext()).getLoginUser().getName());
			comment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));

			new CommentTask().execute(comment);
			break;
		default:
			break;
		}
	}

	private final class CommentTask extends AsyncTask<Comment, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Comment... params) {
			try {
				return CommentService.addComment(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				dismiss();
				CustomToast.make(getActivity()).setText("评论成功").show();
			} else {
				CustomToast.make(getActivity()).setText("评论失败").show();
			}
		}

	}
}
